package com.iemes.controller.craft;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.BrandFormMap;
import com.iemes.entity.BrandModelFormMap;
import com.iemes.entity.ClientFormMap;
import com.iemes.entity.ProcessTestFormMap;
import com.iemes.entity.ProcessTestInfoFormMap;
import com.iemes.entity.ProcessTestLocaFormMap;
import com.iemes.entity.ProcessTestReqortFormMap;
import com.iemes.entity.ProcessTestSetFormMap;
import com.iemes.entity.ProcessTestTimeFourFormMap;
import com.iemes.entity.ProcessTestTimeOneFormMap;
import com.iemes.entity.ProcessTestTimeThreeFormMap;
import com.iemes.entity.ProcessTestTimeTwoFormMap;
import com.iemes.entity.ShapeMachineFormMap;
import com.iemes.entity.ShapeMachineFormTypeMap;
import com.iemes.entity.TableFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.mapper.BrandMapper;
import com.iemes.mapper.BrandModelMapper;
import com.iemes.mapper.client.ClientMapper;
import com.iemes.mapper.craft.ProcessTestInfoMapper;
import com.iemes.mapper.craft.ProcessTestLocaMapper;
import com.iemes.mapper.craft.ProcessTestMapper;
import com.iemes.mapper.craft.ProcessTestReqortMapper;
import com.iemes.mapper.craft.ProcessTestSetMapper;
import com.iemes.mapper.craft.ProcessTestTimeFourMapper;
import com.iemes.mapper.craft.ProcessTestTimeOneMapper;
import com.iemes.mapper.craft.ProcessTestTimeThreeMapper;
import com.iemes.mapper.craft.ProcessTestTimeTwoMapper;
import com.iemes.mapper.craft.TableMapper;
import com.iemes.mapper.machine.ShapeMachineMapper;
import com.iemes.plugin.PageView;
import com.iemes.upload.UploadUtil;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;

@Controller
@RequestMapping("process")
public class ProcessTestController extends BaseController {
	@Inject
	private ProcessTestMapper processTestMapper;
	@Inject
	private ClientMapper clientMapper;
	@Inject
	private BrandMapper brandMapper;
	@Inject
	private BrandModelMapper brandModelMapper;
	@Inject
	private ProcessTestInfoMapper infoMapper;
	@Inject
	private ProcessTestLocaMapper locaMapper;
	@Inject
	private ProcessTestSetMapper setMapper;
	@Inject
	private ProcessTestTimeOneMapper oneMapper;
	@Inject
	private ProcessTestTimeTwoMapper twoMapper;
	@Inject
	private ProcessTestTimeThreeMapper threeMapper;
	@Inject
	private ProcessTestTimeFourMapper fourMapper;
	@Inject
	private ShapeMachineMapper shapeMachine;
	@Inject
	private TableMapper tableMapper;
	@Inject
	private ProcessTestReqortMapper reqortMapper;

	// 进入试模模式
	@RequestMapping(value = "machine", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	public String machine(Model model, HttpSession session) {
		if (session.getAttribute("mapIndex") == null) {
			session.setAttribute("mapIndex", 0);
		}
		// 要查机台表
		ShapeMachineFormMap shapeMachineFormMap = new ShapeMachineFormMap();
		shapeMachineFormMap.put("state", 1);
		List<ShapeMachineFormMap> findByWhere = shapeMachine
				.findByWhere(shapeMachineFormMap);
		model.addAttribute("shapeMachine", findByWhere);
		return Common.BACKGROUND_PATH + "/technology/process/testmold_add";
	}

	// 按机台号查询
	@RequestMapping(value = "machinechen_Entity", method = RequestMethod.POST)
	public String machines(Model model, HttpSession session) {
		ProcessTestFormMap processTestFormMap = getFormMap(ProcessTestFormMap.class);
		TableFormMap tableFormMap = getFormMap(TableFormMap.class);
		Integer nameId = Integer.parseInt(tableFormMap.get("machine_no")
				.toString());
		try {
			// 开始日期与时间

			// 查机器传过来的数据表
			List<Map<String, Object>> listTable = tableMapper
					.getListTable(tableFormMap);
			// 修改机器字段的Key
			if (listTable.get(listTable.size() - 1) != null) {
				listTable.get(listTable.size() - 1).put("machine_date",
						listTable.get(listTable.size() - 1).get("日期"));
				listTable.get(listTable.size() - 1).put("machine_time",
						listTable.get(listTable.size() - 1).get("时间"));
				listTable.get(listTable.size() - 1).put("machine_mold",
						listTable.get(listTable.size() - 1).get("模号" + nameId));
				listTable.get(listTable.size() - 1).put(
						"cycle_machine",
						listTable.get(listTable.size() - 1)
								.get("工艺周期" + nameId));
				listTable.get(listTable.size() - 1).put(
						"cy_machine",
						listTable.get(listTable.size() - 1)
								.get("工艺周期" + nameId));
				listTable.get(listTable.size() - 1).put(
						"target_output",
						listTable.get(listTable.size() - 1).get(
								"设定目标产量" + nameId));
				listTable.get(listTable.size() - 1).put(
						"module_produced",
						listTable.get(listTable.size() - 1).get(
								"已经生产模数" + nameId));
				listTable.get(listTable.size() - 1).put(
						"modulus_need",
						listTable.get(listTable.size() - 1).get(
								"还需生产模数" + nameId));
				listTable.get(listTable.size() - 1).put(
						"production_count",
						listTable.get(listTable.size() - 1).get(
								"产量完成倒计时" + nameId));
			}
			model.addAttribute("listTable", listTable.get(listTable.size() - 1));
			model.addAttribute("tableFormMap", tableFormMap);
			// 保存机台号
			session.setAttribute("nameId", tableFormMap.get("machine_no"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 拿出所有的成型周期时间，计算哪个成型周期时间最小，再通过件数+12个小时+成型周期算出标准产能，
		return Common.BACKGROUND_PATH
				+ "/technology/process/testmold_searchUpd";
	}

	// 保存多份数据
	@RequestMapping(value = "save_Entity", method = RequestMethod.POST)
	public String save(Model model, HttpSession session) {
		TableFormMap tableFormMap = getFormMap(TableFormMap.class);
		model.addAttribute("tableForm", tableFormMap);
		int mapIndex = Integer.parseInt(session.getAttribute("mapIndex")
				.toString());
		if (mapIndex >= 0) {
			session.setAttribute("mapIndex", mapIndex + 1);
			mapIndex = mapIndex + 1;
		}
		session.setAttribute("save_Entity" + mapIndex, tableFormMap);
		// 拿出所有的成型周期时间，计算哪个成型周期时间最小，再通过件数+12个小时+成型周期算出标准产能，
		// 跳回试模模式页面
		// 要查机台表
		ShapeMachineFormMap shapeMachineFormMap = new ShapeMachineFormMap();
		shapeMachineFormMap.put("state", 1);
		List<ShapeMachineFormMap> findByWhere = shapeMachine
				.findByWhere(shapeMachineFormMap);
		model.addAttribute("shapeMachine", findByWhere);
		return Common.BACKGROUND_PATH + "/technology/process/testmold_add";
	}

	// 进入编写试模评估报告前先进入选择模具号与机台号
	@RequestMapping(value = "assessmentMachine_Entity")
	public String assessmentMo(Model model, HttpSession session) {
		List<Map<String, Object>> listMap = new ArrayList<>();
		if (session.getAttribute("mapIndex")==null||session.getAttribute("mapIndex").equals(0)) {
			return Common.BACKGROUND_PATH + "/technology/process/testmold_machine";
		}
		int mapIndex = Integer.parseInt(session.getAttribute("mapIndex")
				.toString());
		for (int i = 1; i <= mapIndex; i++) {
			if (session.getAttribute("save_Entity" + i) != null) {
				listMap.add((Map<String, Object>) session
						.getAttribute("save_Entity" + i));
			}

		}
		// 拿取所有的机台号（不能有重复,不能对原数据-删除-修改-插入）
		List<Map<String, Object>> machine = new ArrayList<>();
		machine.add(listMap.get(0));
		for (int i = 0; i < listMap.size()-1; i++) {
			boolean ok = true;
			for (int j = 0; j < machine.size(); j++) {
				System.out.println(machine);
				if (listMap.get(i + 1).get("machine_no")
						.equals(machine.get(j).get("machine_no"))) {
					ok=false;
				}
			}
			if (ok) {
				machine.add(listMap.get(i + 1));
			}
		}

		// 拿取所有的机台号（不能有重复,不能对原数据-删除-修改-插入）
		List<Map<String, Object>> machineMold = new ArrayList<>();
		machineMold.add(listMap.get(0));
		for (int i = 0; i < listMap.size()-1; i++) {
			boolean ok = true;
			for (int j = 0; j < machineMold.size(); j++) {
				System.out.println(machineMold);
				if (listMap.get(i + 1).get("machine_mold")
						.equals(machineMold.get(j).get("machine_mold"))) {
					ok=false;
				}
			}
			if (ok) {
				machineMold.add(listMap.get(i + 1));
			}
		}

		model.addAttribute("machine", machine);
		model.addAttribute("machineMold", machine);
		// 拿出所有的成型周期时间，计算哪个成型周期时间最小，再通过件数+12个小时+成型周期算出标准产能，
		// 进入编写试模评估报告页面
		return Common.BACKGROUND_PATH + "/technology/process/testmold_machine";
	}

	// 选择模具号进入编写试模评估报告
	@RequestMapping(value = "assessment_Entity")
	public String assessment(Model model, HttpSession session) {
		String paraMachine = getPara("machine_no");
		String paraMold = getPara("machine_mold");
		List<Map<String, Object>> listMap = new ArrayList<>();
		// 拿取最优方案
		int mapIndex = Integer.parseInt(session.getAttribute("mapIndex")
				.toString());
		for (int i = 1; i <= mapIndex; i++) {
			Map<String, Object> mapList = (Map<String, Object>) session
					.getAttribute("save_Entity" + i);
			if (paraMold.equals(mapList.get("machine_mold"))
					&& mapList.get("machine_no").equals(paraMachine)) {
				listMap.add(mapList);
			}
		}
		//有问题
		Map<String, Object> map = new HashMap<>();
		for (int i = 0; i < 1; i++) {
			for (int j = 1; j < listMap.size(); j++) {
				if (Integer.parseInt(listMap.get(i).get("cy_machine")
						.toString()) > Integer.parseInt(listMap.get(j)
						.get("cy_machine").toString())) {
					map = listMap.get(j);
					listMap.get(i).put("cy_machine",
							listMap.get(j).get("cy_machine"));
					listMap.get(j).put("cy_machine",
							listMap.get(i).get("cy_machine"));

				}
			}
		}
		if (map.size()!=0) {
			model.addAttribute("listMap", map);
		} else {
			model.addAttribute("listMap", listMap.get(0));
		}
		// 拿出所有的成型周期时间，计算哪个成型周期时间最小，再通过件数+12个小时+成型周期算出标准产能，
		// 进入编写试模评估报告页面
		return Common.BACKGROUND_PATH
				+ "/technology/process/testmold_assessment";
	}

	// 编写试模评估报告上传图片
	@ResponseBody
	@RequestMapping(value = "imgUpb_Entity", method = RequestMethod.POST)
	public String imgUpb(
			@RequestParam(value = "price", required = false) MultipartFile file,
			HttpServletRequest request, HttpSession session) {
		UploadUtil uploadUtil = new UploadUtil();
		String imagePath="";
		if (!file.isEmpty()) {
			// 原文件名（包含后缀名）
			String getUploadFileName = file.getOriginalFilename();
			// 后缀名
			String getUploadContentType = getUploadFileName
					.substring(getUploadFileName.lastIndexOf(".") + 1);

			try {
				uploadUtil.uploadImage2(request, file, getUploadContentType,
						getUploadFileName);
				imagePath = uploadUtil.getImagePath2();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return imagePath;
	}

	// 保存编写试模评估报告
	@ResponseBody
	@Transactional(readOnly = false)
	@RequestMapping(value = "storage_Entity", method = RequestMethod.POST)
	public String storage(HttpSession session) {
		// 都是新增功能
		ProcessTestFormMap processTestFormMap = getFormMap(ProcessTestFormMap.class);
		ProcessTestTimeOneFormMap processTestTimeOneFormMap = getFormMap(ProcessTestTimeOneFormMap.class);
		ProcessTestTimeTwoFormMap processTestTimeTwoFormMap = getFormMap(ProcessTestTimeTwoFormMap.class);
		ProcessTestTimeThreeFormMap processTestTimeThreeFormMap = getFormMap(ProcessTestTimeThreeFormMap.class);
		ProcessTestTimeFourFormMap processTestTimeFourFormMap = getFormMap(ProcessTestTimeFourFormMap.class);
		ProcessTestSetFormMap processTestSetFormMap = getFormMap(ProcessTestSetFormMap.class);
		ProcessTestLocaFormMap processTestLocaFormMap = getFormMap(ProcessTestLocaFormMap.class);
		ProcessTestInfoFormMap processTestInfoFormMap = getFormMap(ProcessTestInfoFormMap.class);
		ProcessTestReqortFormMap processTestReqortFormMap = getFormMap(ProcessTestReqortFormMap.class);
		// 获取request
				HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
								.getRequestAttributes()).getRequest();
						// 通过工具类获取当前登录的bean
				UserFormMap userFormMap = (UserFormMap) Common.findUserSession(request);
				try {
					oneMapper.addEntity(processTestTimeOneFormMap);
					processTestFormMap.put("TimeOne",
							processTestTimeOneFormMap.get("id"));
					twoMapper.addEntity(processTestTimeTwoFormMap);
					processTestFormMap.put("TimeTwo",
							processTestTimeTwoFormMap.get("id"));
					threeMapper.addEntity(processTestTimeThreeFormMap);
					processTestFormMap.put("TimeThree",
							processTestTimeThreeFormMap.get("id"));
					fourMapper.addEntity(processTestTimeFourFormMap);
					processTestFormMap.put("TimeFour",
							processTestTimeFourFormMap.get("id"));
					setMapper.addEntity(processTestSetFormMap);
					processTestFormMap.put("TestSet", processTestSetFormMap.get("id"));
					locaMapper.addEntity(processTestLocaFormMap);
					processTestFormMap
							.put("TestLoca", processTestLocaFormMap.get("id"));
					processTestInfoFormMap.put("Person_Id", userFormMap.get("id"));
					infoMapper.addEntity(processTestInfoFormMap);
					processTestFormMap
							.put("TestInfo", processTestInfoFormMap.get("id"));
					// 拿图片的路径
					processTestReqortFormMap.put("ImageUpload","<img onclick=\\\'ok(this)\\\' height=\\\'30\\\' width=\\\'30\\\' src=\\\'http://localhost:9100/TY-ERP"+ processTestReqortFormMap.get("ImageUpload") + "\\\'/>");
					processTestReqortFormMap.put("Date", DateUtils.getStringDate());
					reqortMapper.addEntity(processTestReqortFormMap);
					processTestFormMap.put("TestRepport",
							processTestReqortFormMap.get("id"));
					processTestFormMap.put("status", 1);
					processTestFormMap.put("Enactment_Date", DateUtils.getStringDate());
					processTestMapper.addEntity(processTestFormMap);
				} catch (Exception e) {
					e.printStackTrace();
				}

				return "success";
	}

	@RequestMapping(value = "testmold", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	public String examinepru(Model model) {
		// 客户
		List<ClientFormMap> clientFormMaps = clientMapper
				.findByWhere(new ClientFormMap());
		model.addAttribute("client", clientFormMaps);
		model.addAttribute("res", findByRes());
		// 用料品牌
		List<BrandFormMap> brandFormMaps = brandMapper
				.findByWhere(new BrandFormMap());
		// 用料型号
		List<BrandModelFormMap> brandModelFormMaps = brandModelMapper
				.findByWhere(new BrandModelFormMap());
		// 机器型号
		List<ShapeMachineFormTypeMap> shapeMachineFormTypeMaps = baseMapper
				.findByWhere(new ShapeMachineFormTypeMap());
		model.addAttribute("brand", brandFormMaps);
		model.addAttribute("shape", shapeMachineFormTypeMaps);
		model.addAttribute("brandmodel", brandModelFormMaps);
		return Common.BACKGROUND_PATH + "/technology/process/testmold_list";
	}

	@ResponseBody
	@RequestMapping("testmold_findByPage")
	public PageView findByPage(String pageNow, String pageSize) {
		ProcessTestFormMap processTestFormMap = getFormMap(ProcessTestFormMap.class);
		if (processTestFormMap.get("Mold_Number") != null) {
			processTestFormMap.put("Mold_Number",
					"%" + processTestFormMap.get("Mold_Number") + "%");
		}
		processTestFormMap.put("status", 1);
		processTestFormMap = toFormMap(processTestFormMap, pageNow, pageSize,
				processTestFormMap.getStr("orderby"));
		List<ProcessTestFormMap> findByPage = processTestMapper
				.findByPage(processTestFormMap);
		pageView.setRecords(findByPage);
		return pageView;
	}

	// 查看工艺
	@RequestMapping(value = "testmold_edit")
	public String craft_edit(Model model) {
		String id = getPara("id");
		String para = getPara("Mold_Number");
		if (Common.isNotEmpty(id)) {
			ProcessTestFormMap processTest = processTestMapper.findbyFrist(
					"id", id, ProcessTestFormMap.class);
			String str = processTest.getStr("TimeOne");
			ProcessTestTimeOneFormMap timeOne = oneMapper.findbyFrist("id",
					processTest.get("TimeOne").toString(),
					ProcessTestTimeOneFormMap.class);
			ProcessTestTimeTwoFormMap timeTwo = twoMapper.findbyFrist("id",
					processTest.get("TimeTwo").toString(),
					ProcessTestTimeTwoFormMap.class);
			ProcessTestTimeThreeFormMap timeThree = threeMapper.findbyFrist(
					"id", processTest.get("TimeThree").toString(),
					ProcessTestTimeThreeFormMap.class);
			ProcessTestTimeFourFormMap timeFour = fourMapper.findbyFrist("id",
					processTest.get("TimeFour").toString(),
					ProcessTestTimeFourFormMap.class);
			ProcessTestInfoFormMap infoFormMap = infoMapper.findbyFrist("id",
					processTest.get("TestInfo").toString(),
					ProcessTestInfoFormMap.class);
			ProcessTestLocaFormMap locaFormMap = locaMapper.findbyFrist("id",
					processTest.get("TestLoca").toString(),
					ProcessTestLocaFormMap.class);
			ProcessTestSetFormMap setFormMap = setMapper.findbyFrist("id",
					processTest.get("TestSet").toString(),
					ProcessTestSetFormMap.class);
			model.addAttribute("processTest", processTest);
			model.addAttribute("timeOne", timeOne);
			model.addAttribute("timeTwo", timeTwo);
			model.addAttribute("timeThree", timeThree);
			model.addAttribute("timeFour", timeFour);
			model.addAttribute("infoFormMap", infoFormMap);
			model.addAttribute("locaFormMap", locaFormMap);
			model.addAttribute("setFormMap", setFormMap);
		}
		if (Integer.valueOf(getPara("status")) == 1) {
			return Common.BACKGROUND_PATH
					+ "/technology/process/testmold_editUpd";
		} else {
			return Common.BACKGROUND_PATH + "/technology/process/testmold_edit";
		}
	}

	// 修改工艺操作
	@ResponseBody
	@RequestMapping("testmold_editEntity")
	@SystemLog(module = "试模工艺", methods = "试模工艺-修改工艺")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional
	public String editEntity() throws Exception {
		// 修改工艺为添加最新工艺，保存原来工艺，即为新增工艺，保存日期不一样
		ProcessTestFormMap processTestFormMap = getFormMap(ProcessTestFormMap.class);
		ProcessTestTimeOneFormMap processTestTimeOneFormMap = getFormMap(ProcessTestTimeOneFormMap.class);
		ProcessTestTimeTwoFormMap processTestTimeTwoFormMap = getFormMap(ProcessTestTimeTwoFormMap.class);
		ProcessTestTimeThreeFormMap processTestTimeThreeFormMap = getFormMap(ProcessTestTimeThreeFormMap.class);
		ProcessTestTimeFourFormMap processTestTimeFourFormMap = getFormMap(ProcessTestTimeFourFormMap.class);
		ProcessTestInfoFormMap processTestInfoFormMap = getFormMap(ProcessTestInfoFormMap.class);
		ProcessTestLocaFormMap processTestLocaFormMap = getFormMap(ProcessTestLocaFormMap.class);
		ProcessTestSetFormMap processTestSetFormMap = getFormMap(ProcessTestSetFormMap.class);
		try {
			oneMapper.addEntity(processTestTimeOneFormMap);
			processTestFormMap.put("TimeOne",
					processTestTimeOneFormMap.get("id"));
			twoMapper.addEntity(processTestTimeTwoFormMap);
			processTestFormMap.put("TimeTwo",
					processTestTimeTwoFormMap.get("id"));
			threeMapper.addEntity(processTestTimeThreeFormMap);
			processTestFormMap.put("TimeThree",
					processTestTimeThreeFormMap.get("id"));
			fourMapper.addEntity(processTestTimeFourFormMap);
			processTestFormMap.put("TimeFour",
					processTestTimeFourFormMap.get("id"));
			setMapper.addEntity(processTestSetFormMap);
			processTestFormMap.put("TestSet", processTestSetFormMap.get("id"));
			locaMapper.addEntity(processTestLocaFormMap);
			processTestFormMap
					.put("TestLoca", processTestLocaFormMap.get("id"));
			infoMapper.addEntity(processTestInfoFormMap);
			processTestFormMap
					.put("TestInfo", processTestInfoFormMap.get("id"));
			processTestMapper.editEntity(processTestFormMap);
		} catch (Exception e) {
			return "false";
		}

		return "success";
	}

	// 删除工艺操作
	@ResponseBody
	@RequestMapping("testmold_deleteEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "试模管理", methods = "试模管理-删除工艺")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() {
		ProcessTestFormMap processTestFormMap = getFormMap(ProcessTestFormMap.class);
		String[] ids = getParaValues("ids");
		String arr = ids[0];
		String[] str = arr.split(",");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (int i = 0; i < str.length; i++) {
			// 先查询子表的ID，修改子表后再修改父表
			try {
				processTestFormMap.put("id", str[i]);
				processTestFormMap.put("status", 2);
				processTestFormMap.put("Enactment_Date", sdf.format(new Date())
						.toString());
				processTestMapper.editEntity(processTestFormMap);
			} catch (Exception e) {
				return "false";
			}
		}
		return "success";
	}

}
